package com.xzone.material.security.service

import com.xzone.material.authority.service.PermissionService
import com.xzone.material.security.MyUser
import com.xzone.material.user.service.UserService
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service

@Service
class SecurityUserDetailsServiceImpl(val userService: UserService, val permissionService: PermissionService) :
    UserDetailsService {
    override fun loadUserByUsername(username: String?): UserDetails {
        if (username == null) {
            throw UsernameNotFoundException("用户名不能为空")
        }

        val userEntity = userService.findByAccount(username) ?: throw UsernameNotFoundException("用户不存在")

        // 获取权限信息
        val userPermissionCodes = permissionService.getUserPermissionCodeList(userEntity.id)

        return MyUser(
            userEntity.id,
            username,
            userEntity.password,
            AuthorityUtils.createAuthorityList(userPermissionCodes)
        )
    }
}
